import { userLoginService, userGetInfoService } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken() || null,
  userInfo: {},
  routes: constantRoutes // 默认路由
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

const actions = {
  async login(context, data) {
    const token = await userLoginService(data)
    context.commit('setToken', token)
    // context.commit('setToken', '123456')
  },
  async getUserInfo(context) {
    const userInfo = await userGetInfoService()
    context.commit('setUserInfo', userInfo)
    return userInfo // 将用户信息作为数据返回
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('setUserInfo', {})
    resetRouter() // 重置路由
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
